// AddPassword.java
package com.example.passwordguard;

import android.app.AlertDialog;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;

public class AddPassword extends AppCompatActivity {
    private EditText appNameInput, usernameInput, passwordInput;
    private PasswordDatabase dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_password);

        dbHelper = new PasswordDatabase(this);
        appNameInput = findViewById(R.id.appNameInput);
        usernameInput = findViewById(R.id.usernameInput);
        passwordInput = findViewById(R.id.passwordInput);
        Button saveButton = findViewById(R.id.saveButton);

        saveButton.setOnClickListener(v -> savePassword());
    }

    private void savePassword() {
        String app = appNameInput.getText().toString().trim();
        String user = usernameInput.getText().toString().trim();
        String pass = passwordInput.getText().toString().trim();

        if (app.isEmpty() || user.isEmpty() || pass.isEmpty()) {
            showMessage("错误", "所有字段必须填写");
            return;
        }

        if (dbHelper.addPassword(app, user, pass)) {
            showMessage("成功", "密码已保存");
            clearFields();
        } else {
            showMessage("错误", "保存失败");
        }
    }

    private void showMessage(String title, String message) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton("确定", null)
                .show();
    }

    private void clearFields() {
        appNameInput.setText("");
        usernameInput.setText("");
        passwordInput.setText("");
    }
}